package com.heima.filter;


import com.heima.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;


@Component
@Slf4j
public class AuthorizeFilter implements GlobalFilter {
    //定义放行路径
    List<String> urlList = Arrays.asList(
            "/login/in"
    );

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //先获取请求和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获取请求路径
        String reqUrl = request.getURI().getPath();

        for (String path : urlList) {   //放行不用拦截的路径
            if (reqUrl.contains(path)) {
              return  chain.filter(exchange);
            }
        }

        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isEmpty(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);// 如果token不存在，向客户端返回错误提示信息
            response.setComplete();
        }
        try {

            Claims claims = AppJwtUtil.getClaimsBody(token);

            if (AppJwtUtil.verifyToken(claims) > 0) {
                response.setStatusCode(HttpStatus.UNAUTHORIZED);// 如果token过期，向客户端返回错误提示信息
                response.setComplete();
            }

            Integer id = claims.get("id", Integer.class);   //解析JWT令牌信息

            //把用户id设置到请求头中，传递到各个微服务
            ServerHttpRequest serverHttpRequest = request.mutate().header("user", String.valueOf(id)).build();
            exchange.mutate().request(serverHttpRequest).build();

        } catch (Exception e) {
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }



        return chain.filter(exchange);

    }
}
